<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { useAnalysisStore } from '@/stores/analysisStore'

const props = defineProps({
  city: {
    type: String,
    required: true
  }
})

const analysisStore = useAnalysisStore()
const chartContainer = ref(null)
let chart = null
const loading = ref(false)

const initChart = () => {
  if (!chartContainer.value) return
  
  // 如果图表已存在，先销毁
  if (chart) {
    chart.dispose()
  }
  
  chart = echarts.init(chartContainer.value)
  chart.showLoading()
}

const loadData = async () => {
  if (!props.city) return
  
  loading.value = true
  try {
    const data = await analysisStore.fetchPriceDistribution(props.city)
    renderChart(data)
  } catch (error) {
    console.error('加载价格分布数据失败:', error)
  } finally {
    loading.value = false
    if (chart) {
      chart.hideLoading()
    }
  }
}

const renderChart = (data) => {
  if (!chart) return
  
  // 确保数据格式正确
  if (!data || !data.ranges || !data.counts) {
    console.error('价格分布数据格式不正确:', data)
    return
  }
  
  const option = {
    title: {
      text: `${props.city}房价分布`,
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c}套'
    },
    xAxis: {
      type: 'category',
      data: data.ranges,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '房源数量'
    },
    series: [
      {
        name: '房源数量',
        type: 'bar',
        data: data.counts,
        itemStyle: {
          color: '#5470c6'
        },
        emphasis: {
          itemStyle: {
            color: '#3a56b4'
          }
        },
        barWidth: '60%'
      }
    ],
    grid: {
      left: '5%',
      right: '5%',
      bottom: '15%',
      containLabel: true
    }
  }
  
  chart.setOption(option)
}

const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

watch(() => props.city, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    loadData()
  }
}, { immediate: false })

onMounted(() => {
  initChart()
  if (props.city) {
    loadData()
  }
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 